/*
  Tên:Nguyễn Văn Huy
  MSSV:11374891
  Lớp:DHTH7DLT
  Ngày hoàn thành:28/04/2012
  */
#include "quanlybansach.h"
#include "ui_quanlybansach.h"
#include <QMessageBox>
#include <QtSql>
#include <QInputDialog>
#include <QPalette>
#include <QTextCursor>
#include <QTextCursor>
#include <QTextFrame>
#include <QTextTable>
#include <QTextFrame>
#include <QPrinter>
#include <QPrintDialog>
#include "frtheloai.h"
#include <QMainWindow>
#include "sqltreemodel.h"
#include "frsach.h"
#include <QDebug>
#include "frtacgia.h"
#include"frmkhachhang.h"
#include "frmquydinh.h"
#include<QStringList>
#include<QCompleter>
#include "frbaocaoton.h"
#include "frbaocaocongno.h"
#include "frdanhsachsach.h"
QuanLyBanSach::QuanLyBanSach(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::QuanLyBanSach)
{
    ui->setupUi(this);
    DB=new MySqlConnection();
     LoaTree();
    //connect(ui->treeSach->selectionMode(),SIGNAL(selectionChanged(const QItemSelection &,const QItemSelection &),this,SLOT(clicktree())));
    connect(ui->actionDangXuat,SIGNAL(triggered()),this,SLOT(onActionexitTriggered()));
    connect(ui->actionThoat,SIGNAL(triggered()),this,SLOT(ThoatPM()));
    connect(ui->actionThemTheLoai,SIGNAL(triggered()),this,SLOT(ThemTheLoai()));
    connect(this,SIGNAL(signalLCDNumber()),this,SLOT(CapNhapTongTien()));
    connect(ui->actionThemSach,SIGNAL(triggered()),this,SLOT(ThemSach()));
    connect(ui->actionThemTG,SIGNAL(triggered()),this,SLOT(ThemTacGia()));
    connect(ui->actionThemKhachHang,SIGNAL(triggered()),this,SLOT(ThemKhachHang()));
    connect(ui->actionCapNhapPB,SIGNAL(triggered()),this,SLOT(CapNhatPM()));
    connect(ui->btlammoigh,SIGNAL(clicked()),this,SLOT(lammoigiohang()));
    connect(ui->actionQuyDinh,SIGNAL(triggered()),this,SLOT(ThemQuyDinh()));
    connect(ui->actionBaocaocongno,SIGNAL(triggered()),this,SLOT(Baocaocongno()));
    connect(ui->actionDanhsachsach,SIGNAL(triggered()),this,SLOT(danhsachsach()));
    //connect(ui->btnChon,SIGNAL(clicked()),this,SLOT(chonKhachHang()));
    //connect(ui->txtidkhachtimkiem,SIGNAL(textChanged(QString)),this,SLOT(txtChangeMaKH()));
    //connect(ui->txtidkhachtimkiem, SIGNAL(textChanged(QString)), SLOT(on_txttenkhachhangtimkiem_textChanged(QString )));
    ui->txtgiamgia->setValidator(new QDoubleValidator(0,99,2,this));
    ui->tbgiohang->resizeColumnsToContents();
    ui->tbgiohang->horizontalHeader()->setStretchLastSection(1);
    ui->btaddcart->setDisabled(1);
    ui->bteditcart->setDisabled(1);
    ui->btxemhoadon->setDisabled(1);
    ui->btupdatestock->setDisabled(1);
    ui->txtgiamgia->setValidator(new QDoubleValidator(0,99,2,this));
    ui->btInHoaDon->setDisabled(1);
    ui->btthanhtoan->setDisabled(1);

    //ui->btclear->setDisabled(1);
    ui->btlammoigh->setDisabled(1);
    timkhachhang();

}

QuanLyBanSach::~QuanLyBanSach()
{
    delete ui;
}

void QuanLyBanSach::ThemSach()
{
       frSach *newsach;
       newsach =new frSach();
       newsach->exec();

}

void QuanLyBanSach::ThemTheLoai()
{
    frTheLoai dialog(this);
    if(dialog.exec()==QDialog::Accepted)
    {
         LoaTree();
    }

}

void QuanLyBanSach::ThemTacGia()
{
    frTacGia *newTacgia;
    newTacgia =new frTacGia();
    newTacgia->exec();
}

void QuanLyBanSach::ThemKhachHang()
{
    frmKhachHang newkhachhang(this);
   if(newkhachhang.exec()==QDialog::Accepted)
   {
       timkhachhang();
   }
}

void QuanLyBanSach::ThemQuyDinh()
{
    frmQuyDinh *frm=new frmQuyDinh();
    frm->exec();
}

void QuanLyBanSach::InHoaDon()
{
 #ifndef QT_NO_PRINTER
    QPrinter printer;

        QPrintDialog *dialog = new QPrintDialog(&printer, this);
        dialog->setWindowTitle(tr("Print Document"));
        if (ui->txtchinhsua->textCursor().hasSelection())
            dialog->addEnabledOption(QAbstractPrintDialog::PrintSelection);
        if (dialog->exec() != QDialog::Accepted)
            return;

        ui->txtchinhsua->print(&printer);
        ui->txtchinhsua->clear();
    #endif
}

void QuanLyBanSach::ThongTinPM()
{
    QMessageBox::about(this,"","thong tin phan mem ");
}

void QuanLyBanSach::CapNhatPM()
{

}

void QuanLyBanSach::ThoatPM()
{
    qApp->quit();
}

void QuanLyBanSach::DangXuat()
{

}

void QuanLyBanSach::onActionexitTriggered()
{
    QMessageBox exit;
    exit.information(this,QString::fromUtf8("Thông Báo"),QString::fromUtf8("B?n có ch?c ch?n mu?n thoát"));
    exit.setWindowTitle("Exit");
    exit.setStandardButtons(QMessageBox::Close|QMessageBox::Cancel);
    exit.setDefaultButton(QMessageBox::Close);
    int ret=exit.exec();
    switch(ret) {
        case QMessageBox::Close:
        close();
        break;
        case QMessageBox::Default:
        break;
    }
}

void QuanLyBanSach::Themvaogiohang()
{
    bool ok;
    int qty = QInputDialog::getInt(this, QString::fromUtf8("Nhập số lượng"),
                                         QString::fromUtf8("Số lượng"),1,1,1000,2,&ok,Qt::Dialog);
    int tonkho=ui->txtluongton->text().toInt(0,10);
    int luongtontoithieu=20;
    int luongtonsaukhiban=tonkho-qty;
    if(luongtonsaukhiban<luongtontoithieu)
    {
        QMessageBox::warning(this,QString::fromUtf8("Thông Báo"),QString::fromUtf8("lượng tồn tối thiểu phải lớn hơn 20 ?"));
        return;
    }
    float price = ui->txtgiaban->text().toFloat(&ok);
    ui->tbgiohang->setRowCount(sn+1);

    ui->tbgiohang->setItem(sn,0,new QTableWidgetItem(ui->txtid->text()));
    ui->tbgiohang->setItem(sn,1,new  QTableWidgetItem(ui->txttensach->text()));
    ui->tbgiohang->setItem(sn,2,new QTableWidgetItem(ui->txttheloai->text()));
    ui->tbgiohang->setItem(sn,3,new QTableWidgetItem(ui->txtgiaban->text()));
    ui->tbgiohang->setItem(sn,4,new QTableWidgetItem(ui->txtgiamgia->text()));
    ui->tbgiohang->setItem(sn,5,new QTableWidgetItem(QString("%1").arg(qty)));
    ui->tbgiohang->setItem(sn,6,new QTableWidgetItem(QString("%1").arg(qty*price)));
    ui->tbgiohang->resizeColumnsToContents();

    ui->tbgiohang->horizontalHeader()->setStretchLastSection(1);
   // ui->btInHoaDon->setEnabled(1);
    ui->btthanhtoan->setEnabled(1);
    ui->btxemhoadon->setEnabled(1);
    ui->btlammoigh->setEnabled(1);
    //ui->btclear->setEnabled(1);
    emit signalLCDNumber();
    sn++;

}

void QuanLyBanSach::CapNhapTongTien()
{
    //bool ok;
    int rows=ui->tbgiohang->rowCount();
    int first;
    float phantramgiamgia=ui->txtgiamgia->text().toFloat(0);
    if(phantramgiamgia>99)
    {
        QMessageBox::warning(this,QString::fromUtf8("Thông Báo"),QString::fromUtf8("Quá ph?n trãm gi?m giá (nh? hõn 100)?"));
        return;
    }
    for(first=0;first<=rows-1;first++)
    {
        totalPayable+=ui->tbgiohang->item(first,6)->text().toFloat(0);
    }
    ui->tongtienlcdNumber->display(totalPayable-phantramgiamgia*0.01*totalPayable);
    totalPayable=0;


}

void QuanLyBanSach::XemHoaDon()
{
    QTextCursor cursor(ui->txtchinhsua->textCursor());
    ui->txtchinhsua->setReadOnly(1);
    cursor.movePosition(QTextCursor::Start);
    QTextFrame *topFrame = cursor.currentFrame();
    QTextFrameFormat topFrameFormat = topFrame->frameFormat();
    topFrameFormat.setPadding(0);
    topFrame->setFrameFormat(topFrameFormat);

    QTextCharFormat textFormat;
    QTextCharFormat boldFormat;
    boldFormat.setFontWeight(QFont::Bold);
    QString idsplit=ui->txttenkhachhangtimkiem->text();
    QStringList slist=idsplit.split("-:");
    cursor.insertText(QString::fromUtf8("Hóa Đơn Bán Hàng"), boldFormat);
    cursor.insertBlock();
    cursor.insertText(QString::fromUtf8("Tên khách hàng : %1").arg(slist[0]));
    cursor.insertBlock();
    cursor.insertText(QString::fromUtf8("Địa chỉ : %1").arg(ui->txtdiachi->text()));
    cursor.insertBlock();
    cursor.insertText(QString::fromUtf8("Hóa Đơn số :123456"));

    QDate date = QDate::currentDate();
    cursor.insertBlock();
    cursor.insertText(QString::fromUtf8("Ngày: %1").arg(date.toString("d MMMM yyyy")),textFormat);
    cursor.insertBlock();
    cursor.insertBlock();
    QTextTable *bill=cursor.insertTable(ui->tbgiohang->rowCount() + 1,4);

    cursor = bill->cellAt(0, 0).firstCursorPosition();
    cursor.insertText(QString::fromUtf8("Tên ."), boldFormat);
    cursor = bill->cellAt(0, 1).firstCursorPosition();
    cursor.insertText(QString::fromUtf8("Thể loại ."), boldFormat);
    cursor = bill->cellAt(0, 2).firstCursorPosition();
    cursor.insertText(QString::fromUtf8("số lượng."), boldFormat);
    cursor = bill->cellAt(0, 3).firstCursorPosition();
    cursor.insertText(QString::fromUtf8("Đơn gia"), boldFormat);

    int cartRowCount =ui->tbgiohang->rowCount();
    int initializer;
    for(initializer = 1; initializer<= cartRowCount; initializer++)
    {
        cursor = bill->cellAt(initializer, 0).firstCursorPosition();
        cursor.insertText(tr("%1").arg(ui->tbgiohang->item(initializer-1,1)->text()),boldFormat);
        cursor = bill->cellAt(initializer, 1).firstCursorPosition();
        cursor.insertText(tr("%1").arg(ui->tbgiohang->item(initializer-1,2)->text()),boldFormat);
        cursor = bill->cellAt(initializer, 2).firstCursorPosition();
        cursor.insertText(tr("%1").arg(ui->tbgiohang->item(initializer-1,5)->text()),boldFormat);
        cursor = bill->cellAt(initializer, 3).firstCursorPosition();
        cursor.insertText(tr("%1").arg(ui->tbgiohang->item(initializer-1,3)->text()),boldFormat);

    }
    cursor.atEnd();
    cursor.setPosition(topFrame->lastPosition());
    cursor.insertBlock();
    cursor.insertBlock();
    cursor.insertText(QString::fromUtf8("Giam giá % : "));
    cursor.insertText(tr("%1").arg(ui->txtgiamgia->text()));
    cursor.insertBlock();
    cursor.insertText(QString::fromUtf8("Tổng Tiền  : "));
    cursor.insertText(tr("%1").arg(ui->tongtienlcdNumber->value()));
}

void QuanLyBanSach::LoaTree()
{
    DB->Open();
    QList<int> group_column_indexes;
    group_column_indexes << 0; // group by column 0... can be any combination of column indexes
    SqlTreeModel* model=new SqlTreeModel();
    _model=new TasksModel();
    //QString query="select * from khachhang";
    QSqlQuery query(DB->DB);
    query.prepare("SELECT * FROM TheLoai");
    query.exec();
    QString sql="SELECT * FROM TheLoai";
    model->SetQuery(query);
    model->SetGroupByIndexes(group_column_indexes);
    model->SetGroupTitleFormat("Group {0}");
    model->Select();

    //ui->treeSach->setAllColumnsShowFocus(false);
    ui->treeSach->setModel(_model);
    for(int i=0;i<ui->treeSach->model()->rowCount();i++)
        ui->treeSach->setFirstColumnSpanned(i,QModelIndex(),true);
    for (int column = 0; column < _model->columnCount(); ++column)
        ui->treeSach->resizeColumnToContents(column);
    ui->treeSach->expandAll();

    //ui->treeSach->setModel();
   // DB->Close();
}
int QuanLyBanSach::sn = 0;
float QuanLyBanSach::totalPayable = 0;

void QuanLyBanSach::clicktree()
{
   DB->Open();
   QString ids,tensach,giaban,soluongton,tacgia;
   QSqlQuery query(DB->DB),laytentl(DB->DB);
    QVariant id;
    foreach (QModelIndex index,ui->treeSach->selectionModel()->selectedIndexes())
    {
         id=ui->treeSach->model()->data(index,Qt::UserRole);

        //query.prepare("SELECT MaSach,TenSach,TenTacGia,GiaBan,SoLuongTon FROM TacGia left join Sach on TacGia.MaTacGia=Sach.MaTacGia where MaSach=:MaSach");

       //ui->txtgiaban->setText(query.value(2).toString());
       //ui->txtluongton->setText(query.value(3).toString());

        break;
    }

    query.prepare("SELECT MaSach,TenSach,TenTacGia,GiaBan,SoLuongTon,MaTheLoai FROM TacGia left join Sach on TacGia.MaTacGia=Sach.MaTacGia where MaSach=:MaSach");
    query.bindValue(":MaSach",id.toString());
    query.exec();
    query.next();
    laytentl.prepare("SELECT TenTheLoai FROM Sach where MaSach=:MaSach");
    laytentl.bindValue(":MaSach",query.value(5).toString());
    laytentl.exec();
    laytentl.next();
    ui->txttheloai->setText(laytentl.value(0).toString());
    ui->txtid->setText(id.toString());
    ui->txttensach->setText(query.value(1).toString());
    ui->txttacgia->setText(query.value(2).toString());
    ui->txtgiaban->setText(query.value(3).toString());
    ui->txtluongton->setText(query.value(4).toString());
     qDebug()<<laytentl.lastError();
     ui->btaddcart->setEnabled(1);

     //ui->btxemhoadon->setEnabled(1);
     //ui->btthanhtoan->setEnabled(1);
    DB->Close();
}


void QuanLyBanSach::on_treeSach_clicked(const QModelIndex &index)
{
    clicktree();
}

void QuanLyBanSach::Thanhtoan()
{
    //Kiểm tra điều kiện
    /*
      id 1 so luong nhap toi thieu
         2 so luong ton toi thieu nhap
         3 so tien no toi da
         4 so luong ton toi thieu ban
    bool isKT;
    int values=DB->giatTriQuyDinh(1,isKT);
    //Kiểm tra điều kiện số lượng nhập tối thiểu
    if(isKT)
    {
        //viết lệnh
    }
    //Kiểm tra điều kiện số lượng tồn tối thiểu khi nhập
    values=DB->giatTriQuyDinh(2,isKT);
    if(isKT)
    {
        //viết lệnh
    }
    //Kiểm tra điều kiện số tiền nợ tối đa
    values=DB->giatTriQuyDinh(3,isKT);
    if(isKT)
    {
        //viết lệnh
    }
    //Kiểm tra điều kiện số lượng tồn tối thiểu khi bán
    values=DB->giatTriQuyDinh(4,isKT);
    if(isKT)
    {
        //viết lệnh
    }
    */

    int congno=20000;
    float totalAmount =ui->tongtienlcdNumber->value();
    int tienno =ui->txttienno->text().toInt(0,10);
    int idkh=ui->txtidkhachtimkiem->text().toInt(0,10);
    /*int a;
    for(a=0;a <= ui->tbgiohang->rowCount()-1; a++)
    {
        int productID;
        productID=ui->tbgiohang->item(a,0)->text().toInt(0,10);
        QSqlQuery getInStockValue(DB->DB), updateInStockValue(DB->DB);
        getInStockValue.prepare("SELECT SoLuongTon FROM Sach where MaSach= ?");
        getInStockValue.bindValue(0, productID);
        getInStockValue.exec();
        getInStockValue.next();
        int soluonghangbandau=getInStockValue.value(0).toInt(0);
        int soluongltonsaukhiban=soluonghangbandau -ui->tbgiohang->item(a,3)->text().toInt(0,10);

        if(soluongltonsaukhiban<luongtontoithieu)
        {
            QMessageBox::warning(this,QString::fromUtf8("Thông Báo"),QString::fromUtf8("Số lượng tồn sau khi bán của sách   không đưoc vượt quá 20?"));
            return;
        }
    }*/

    if(ui->txtidkhachtimkiem->text().isEmpty())
    {
        QMessageBox::information(this,"thong bao","ban chua nhap thong tin khach hang");
        return;
    }
    if(tienno > congno)
    {
        QMessageBox::warning(this,QString::fromUtf8("Thông Báo"),QString::fromUtf8("Số tiền khách hàng đang nợ vượt quá 20000?"));
        return;
    }
    //End kiểm tra điều kiện
    QSqlQuery querykhachhang(DB->DB),luunocuoi(DB->DB);

    if(ui->txttienno->text().isEmpty())
    {
        //QString datenow=QString::number(QDate::currentDate().month())+"/"+QString::number(QDate::currentDate().year());
        querykhachhang.prepare("UPDATE KhachHang SET Nodau=? WHERE MaKH=? ");

        querykhachhang.bindValue(0,ui->txtnodau->text());
        querykhachhang.bindValue(1,ui->txtidkhachtimkiem->text());

        if(!querykhachhang.exec())
        {
             QMessageBox::critical(this,"Ilegal string",querykhachhang.lastError().text());
             return;
        }
        int a=0;
        luunocuoi.prepare("INSERT INTO Congno (Nocuoi, MaKH) VALUES ( ?, ?)");
        //luunocuoi.bindValue(0,datenow);
        luunocuoi.bindValue(0,a);
        luunocuoi.bindValue(1,ui->txtidkhachtimkiem->text());
        luunocuoi.exec();

    }else if(ui->txttiennops->text()!="")
    {
        //QString datenow=QString::number(QDate::currentDate().month())+"/"+QString::number(QDate::currentDate().year());
        querykhachhang.prepare("INSERT INTO Congno ( Diengiai, Nocuoi, MaKH) VALUES ( ?, ?, ?)");
        //querykhachhang.bindValue(0,datenow);
        querykhachhang.bindValue(0,ui->txtdiengiaino->text());
        querykhachhang.bindValue(1,ui->txttiennops->text());
        querykhachhang.bindValue(2,ui->txtidkhachtimkiem->text());
        querykhachhang.exec();
        if(!querykhachhang.exec())
        {
             QMessageBox::critical(this,"co loi khi thuc thi",querykhachhang.lastError().text());
             return;
        }

    }

    DB->Open();
    if(ui->tongtienlcdNumber->value()==0)
    {return;}

    int giohangrows=ui->tbgiohang->rowCount();
    int first;
    for(first=0;first<=giohangrows-1;first++)
    {
        bool ok;
        int productID;
        productID=ui->tbgiohang->item(first,0)->text().toInt(0,10);
        QSqlQuery getInStockValue(DB->DB), updateInStockValue(DB->DB);
        getInStockValue.prepare("SELECT SoLuongTon FROM Sach where MaSach= ?");
        getInStockValue.bindValue(0, productID);
        getInStockValue.exec();
        getInStockValue.next();
        int soluonghangbandau=getInStockValue.value(0).toInt(0);

        int soluonghangmoi=soluonghangbandau -ui->tbgiohang->item(first,5)->text().toInt(0,10);
        updateInStockValue.prepare("UPDATE Sach SET SoLuongTon = ? WHERE MaSach = ?");
        updateInStockValue.bindValue(0,soluonghangmoi);
        updateInStockValue.bindValue(1,productID);
        updateInStockValue.exec();
    }
    //su ly chi tiet hoa don
            QSqlQuery insertInvoice(DB->DB), getLastInvoiceNumber(DB->DB);
            insertInvoice.prepare("INSERT INTO HoaDon (MaKH,TongTien) VALUES ( ?, ? )");
            insertInvoice.bindValue(0,idkh);
            insertInvoice.bindValue(1,totalAmount);
            insertInvoice.exec();

            //lay ma chi tiet hoa don
            int invoiceNumber;
            getLastInvoiceNumber.exec("SELECT MaHoaDon FROM HoaDon");
            getLastInvoiceNumber.last();
            invoiceNumber=getLastInvoiceNumber.value(0).toInt(0);

            //insert vao hoa don
            int loopInitial, cartRowCount;
            QSqlQuery insertTohoadon(DB->DB);

            cartRowCount=ui->tbgiohang->rowCount();
            for(loopInitial =0;loopInitial<=cartRowCount-1;loopInitial++)
            {
                int ma_sach =ui->tbgiohang->item(loopInitial,0)->text().toInt(0,10);
                int giamgia =ui->tbgiohang->item(loopInitial,4)->text().toInt(0,10);
                int soluong =ui->tbgiohang->item(loopInitial,5)->text().toInt(0,10);
                int thanhtien=ui->tbgiohang->item(loopInitial,6)->text().toInt(0,10);
                insertTohoadon.prepare("INSERT INTO ChiTietHoaDon (MaHoaDon, SoLuong, MaSach, GiamGia, ThanhTien) VALUES (?, ?, ?, ?, ?)");
                insertTohoadon.bindValue(0,invoiceNumber);
                insertTohoadon.bindValue(1,soluong);
                insertTohoadon.bindValue(2,ma_sach);
                insertTohoadon.bindValue(3,giamgia);
                insertTohoadon.bindValue(4,thanhtien);
                if(!insertTohoadon.exec())
                {
                     QMessageBox::critical(this,"kiem tra loi",insertTohoadon.lastError().text());
                }
            }
            QMessageBox::information(this,"Done","thá»±c hiá»‡n hĂ³a Ä‘Æ¡n thĂ nh cĂ´ng, báº¡n cĂ³ thá»ƒ in hĂ³a Ä‘Æ¡n bĂ¢y giá»");
            ui->btthanhtoan->setDisabled(1);
            ui->btInHoaDon->setDisabled(0);
      DB->Close();
}

void QuanLyBanSach::timsach()
{
    DB->Open();
    QString ten,id;
    ten=ui->txttimkiemtensach->text();
    id=ui->txtidsachtk->text();
    if(ui->txttimkiemtensach->text().isEmpty()||ui->txtidsachtk->text().isEmpty())
    {

        QMessageBox::warning(this,"Kiem tra nhap","ban chua nhap du thong tin");
        return;
    }
    QSqlQuery timkiemsach(DB->DB);
    timkiemsach.prepare("SELECT MaSach,TenSach,GiaBan,SoLuongTon,TenTacGia FROM Sach join TacGia where TacGia.MaTacGia=Sach.MaTacGia and MaSach=:MaSach ");
    timkiemsach.bindValue(":MaSach",id);
    //timkiemsach.bindValue(":TenSach",ten);
    timkiemsach.exec();
    if(timkiemsach.next())
    {
        ui->hienthiketquasach->setText("<i>Tim thay</i>");
        ui->txtid->setText(timkiemsach.value(0).toString());
        ui->txttensach->setText(timkiemsach.value(1).toString());
        ui->txtgiaban->setText(timkiemsach.value(2).toString());
        ui->txtluongton->setText(timkiemsach.value(3).toString());
        ui->txttacgia->setText(timkiemsach.value(4).toString());
    }
    else
    {
        ui->hienthiketquasach->setText("<font color=red>Không tìm thay</font>");
         QMessageBox::warning(this,"Không tim thay","Không tìm th?y sách");
    }
    ui->txtidsachtk->clear();
    ui->txttimkiemtensach->clear();
    ui->btaddcart->setEnabled(1);
    DB->Close();
}

void QuanLyBanSach::timkhachhang()
{
    QStringList wordList;
    DB->Open();
    QSqlQuery query(DB->DB);
    query.prepare("select TenKH,MaKH from KhachHang");
    query.exec();
    while(query.next())
        wordList<<query.value(0).toString()+"-:"+ query.value(1).toString();
    QCompleter *completer = new QCompleter(wordList);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    //ui->txttenkh->setCompleter(completer);
    ui->txttenkhachhangtimkiem->setCompleter(completer);

    DB->Close();
}

void QuanLyBanSach::lammoigiohang()
{
    ui->tbgiohang->clearContents();
    ui->tbgiohang->setRowCount(0);
    sn=0;
    ui->tongtienlcdNumber->display(0);
    ui->bteditcart->setDisabled(1);
    ui->btInHoaDon->setDisabled(1);
    ui->btthanhtoan->setDisabled(1);
    ui->txtchinhsua->clear();
}

void QuanLyBanSach::chonKhachHang()
{
    DB->Open();
       QSqlQuery query(DB->DB);
    ui->txttienno->setReadOnly(true);
       if(ui->txtidkhachtimkiem->text() !="")
       {
           QString idkh=ui->txtidkhachtimkiem->text();
            query.prepare("select k.TenKH,k.DiaChi,k.Phone,k.Email,k.Nodau,(sum(c.nocuoi) + k.Nodau) as nocuoi from QLBSach.KhachHang k join QLBSach.Congno c where c.MaKH=k.MaKH and k.maKH = ?");
            query.bindValue(0,idkh);
            query.exec();
            query.next();
            ui->txttenkhachhangtimkiem->setText(query.value(0).toString());
            ui->txtdiachi->setText(query.value(1).toString());
            ui->txtdienthoai->setText(query.value(2).toString());
            ui->txtemail->setText(query.value(3).toString());
            if(query.value(4).isNull())
            {
                ui->txtnodau->clear();
                ui->txttienno->clear();
                ui->txttiennops->clear();
                ui->txtdiengiaino->clear();
                ui->txtdiengiaino->setReadOnly(true);
                ui->txttiennops->setReadOnly(true);
                ui->txtnodau->setReadOnly(false);

            }else
            {
                ui->txtnodau->setText(query.value(4).toString());
                ui->txttienno->setText(query.value(5).toString());
                ui->txtdiengiaino->setReadOnly(false);
                ui->txttiennops->setReadOnly(false);
                ui->txtnodau->setReadOnly(true);
            }

       }else{
               if(ui->txttenkhachhangtimkiem->text().isEmpty())
               {
                   QMessageBox::information(this,"thong bao","ban can nhap ten khach hang ");
                   return;
               }
               QString idsplit=ui->txttenkhachhangtimkiem->text();
               QStringList slist=idsplit.split("-:");
               //bool ok;
               //QString val =;
               ui->txtidkhachtimkiem->setText(slist[1]);

               query.prepare("select k.DiaChi,k.Phone,k.Email,k.Nodau,(sum(c.nocuoi) + k.Nodau) as nocuoikh from QLBSach.KhachHang k join QLBSach.Congno c where c.MaKH=k.MaKH and k.maKH=:Makh");
               query.bindValue(":Makh",slist[1]);
               query.exec();
               query.next();
               ui->txtdiachi->setText(query.value(0).toString());
               ui->txtdienthoai->setText(query.value(1).toString());
               ui->txtemail->setText(query.value(2).toString());
               if(query.value(4).isNull())
               {
                   ui->txtdiengiaino->setReadOnly(true);
                   ui->txttiennops->setReadOnly(true);
                   ui->txtnodau->clear();
                   ui->txttienno->clear();
                   ui->txttiennops->clear();
                   ui->txtdiengiaino->clear();
                   ui->txtnodau->setReadOnly(false);

               }else
               {
                   ui->txtnodau->setText(query.value(3).toString());
                   ui->txttienno->setText(query.value(4).toString());
                   ui->txtdiengiaino->setReadOnly(false);
                   ui->txttiennops->setReadOnly(false);
                   ui->txtnodau->setReadOnly(true);

               }

       }
       DB->Close();
}


void QuanLyBanSach::txtChangeMaKH()
{
    QString idsplit=ui->txttenkhachhangtimkiem->text();
    QStringList slist=idsplit.split("-:");
    ui->txtidkhachtimkiem->setText(slist[1]);
    //bool ok;
    //int maKH=ui->txtidkhachhang->text().toInt(&ok);
    //if(ok)
       // layThongTinKH(maKH);
}

void QuanLyBanSach::clearTTKhachHang()
{
    //ui->txttenkh->clear();
    ui->txtdiachi->clear();
    ui->txtdienthoai->clear();
    ui->txtemail->clear();
    ui->txttienno->clear();
}

void QuanLyBanSach::goibangkh()
{
    frmKhachHang newkhachhang(this);
   if(newkhachhang.exec()==QDialog::Accepted)
   {
       timkhachhang();
   }
}

void QuanLyBanSach::layThongTinKH(int maKH)
{
    ui->txtidkhachtimkiem->setText(QString::number(maKH));
}

void QuanLyBanSach::Baocaocongno()
{
    frbaocaocongno *newbaocaocn=new frbaocaocongno();
    newbaocaocn->exec();
}

void QuanLyBanSach::danhsachsach()
{
    frdanhsachsach *newdanhsach=new frdanhsachsach();
    newdanhsach->exec();
}

//void QuanLyBanSach::on_txttenkhachhangtimkiem_textChanged(const QString &arg1)
//{
 //   QString idsplit=ui->txttenkhachhangtimkiem->text();
  //  QStringList slist=idsplit.split("-:");
 //   ui->txtidkhachtimkiem->setText(slist[1]);
//}//
